from django.db import models
from django.contrib.auth.models import User
from books.models import Book, BookImage
from orders.models import Order


class PricePrediction(models.Model):
    """价格预测记录"""
    
    id = models.BigAutoField(
        primary_key=True,
        db_comment='预测ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='price_predictions',
        db_comment='关联书籍'
    )
    predicted_price_min = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        db_comment='预测最低价'
    )
    predicted_price_max = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        db_comment='预测最高价'
    )
    factors = models.JSONField(
        db_comment='影响因素说明'
    )
    similar_books = models.JSONField(
        db_comment='相似书籍参考'
    )
    model_version = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        db_comment='模型版本'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_comment='预测时间'
    )
    
    class Meta:
        db_table = 'campus_price_prediction'
        db_table_comment = 'AI价格预测记录表'
        verbose_name = '价格预测'
        verbose_name_plural = '价格预测'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.book.title} - ¥{self.predicted_price_min}-¥{self.predicted_price_max}'


class DefectDetection(models.Model):
    """瑕疵检测记录"""
    
    id = models.BigAutoField(
        primary_key=True,
        db_comment='检测ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='defect_detections',
        db_comment='关联书籍'
    )
    image = models.ForeignKey(
        BookImage,
        on_delete=models.CASCADE,
        related_name='defect_detections',
        db_comment='检测图片'
    )
    detection_result = models.JSONField(
        db_comment='检测结果'
    )
    defect_types = models.JSONField(
        default=list,
        blank=True,
        db_comment='瑕疵类型列表'
    )
    condition_score = models.DecimalField(
        max_digits=3,
        decimal_places=1,
        db_comment='成色评分(0-10)'
    )
    annotated_image_url = models.CharField(
        max_length=500,
        null=True,
        blank=True,
        db_comment='标注后图片URL'
    )
    model_version = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        db_comment='模型版本'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_comment='检测时间'
    )
    
    class Meta:
        db_table = 'campus_defect_detection'
        db_table_comment = 'AI瑕疵检测记录表'
        verbose_name = '瑕疵检测'
        verbose_name_plural = '瑕疵检测'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.book.title} - 成色{self.condition_score}分'


class ChatLog(models.Model):
    """聊天记录"""
    
    MESSAGE_TYPE_CHOICES = [
        ('text', '文本'),
        ('ai_suggestion', 'AI建议'),
        ('system', '系统消息'),
    ]
    
    id = models.BigAutoField(
        primary_key=True,
        db_comment='消息ID'
    )
    order = models.ForeignKey(
        Order,
        on_delete=models.CASCADE,
        related_name='chat_logs',
        db_comment='关联订单'
    )
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        db_comment='发送者ID'
    )
    message = models.TextField(
        db_comment='消息内容'
    )
    message_type = models.CharField(
        max_length=20,
        choices=MESSAGE_TYPE_CHOICES,
        default='text',
        db_comment='消息类型'
    )
    ai_parsed_info = models.JSONField(
        null=True,
        blank=True,
        db_comment='AI解析的结构化信息'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_index=True,
        db_comment='发送时间'
    )
    
    class Meta:
        db_table = 'campus_chat_log'
        db_table_comment = '聊天记录表'
        verbose_name = '聊天记录'
        verbose_name_plural = '聊天记录'
        ordering = ['created_at']
        indexes = [
            models.Index(fields=['order', 'created_at']),
        ]
    
    def __str__(self):
        return f'{self.order.order_no} - {self.sender.username}'


class NoteExtraction(models.Model):
    """笔记提取记录"""
    
    id = models.BigAutoField(
        primary_key=True,
        db_comment='提取ID'
    )
    book = models.ForeignKey(
        Book,
        on_delete=models.CASCADE,
        related_name='note_extractions',
        db_comment='关联书籍'
    )
    image = models.ForeignKey(
        BookImage,
        on_delete=models.CASCADE,
        related_name='note_extractions',
        db_comment='笔记图片'
    )
    extracted_text = models.TextField(
        db_comment='提取的文字'
    )
    note_type = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        db_comment='笔记类型'
    )
    keywords = models.JSONField(
        default=list,
        blank=True,
        db_comment='关键词列表'
    )
    confidence_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        db_comment='识别置信度(0-100)'
    )
    model_version = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        db_comment='模型版本'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_comment='提取时间'
    )
    
    class Meta:
        db_table = 'campus_note_extraction'
        db_table_comment = 'AI笔记提取记录表'
        verbose_name = '笔记提取'
        verbose_name_plural = '笔记提取'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.book.title} - 笔记提取'


class ISBNRecognition(models.Model):
    """ISBN识别记录"""
    
    id = models.BigAutoField(
        primary_key=True,
        db_comment='识别ID'
    )
    image = models.ImageField(
        upload_to='isbn_images/',
        db_comment='上传图片'
    )
    recognized_isbn = models.CharField(
        max_length=20,
        null=True,
        blank=True,
        db_comment='识别到的ISBN'
    )
    book_info = models.JSONField(
        null=True,
        blank=True,
        db_comment='书籍信息'
    )
    confidence_score = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        db_comment='识别置信度(0-100)'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        db_comment='用户ID'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        db_comment='识别时间'
    )
    
    class Meta:
        db_table = 'campus_isbn_recognition'
        db_table_comment = 'ISBN识别记录表'
        verbose_name = 'ISBN识别'
        verbose_name_plural = 'ISBN识别'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'ISBN: {self.recognized_isbn or "未识别"}'
